package com.macro.mall.portal.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.google.common.base.Joiner;
import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.exception.Asserts;
import com.macro.mall.common.utils.*;
import com.macro.mall.mapper.*;
import com.macro.mall.model.*;
import com.macro.mall.portal.component.CancelOrderSender;
import com.macro.mall.portal.dao.PortalOrderDao;
import com.macro.mall.portal.dao.PortalOrderItemDao;
import com.macro.mall.portal.dao.SmsCouponHistoryDao;
import com.macro.mall.portal.domain.*;
import com.macro.mall.portal.service.*;
import com.macro.mall.portal.util.HttpKit;
import com.macro.mall.portal.util.KeyedDigestMD5;

import com.macro.mall.portal.vo.*;
import com.macro.mall.security.service.RedisService;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 前台订单管理Service
 * Created by macro on 2020/7/31.
 */
@Service
public class OmsPortalOrderServiceImpl implements OmsPortalOrderService {
    @Autowired
    private UmsMemberService memberService;
    @Autowired
    private OmsCartItemService cartItemService;
    @Autowired
    private UmsMemberReceiveAddressService memberReceiveAddressService;
    @Autowired
    private UmsMemberCouponService memberCouponService;
    @Autowired
    private UmsIntegrationConsumeSettingMapper integrationConsumeSettingMapper;
    @Autowired
    private PmsSkuStockMapper skuStockMapper;
    @Autowired
    private SmsCouponHistoryDao couponHistoryDao;
    @Autowired
    private OmsOrderMapper orderMapper;
    @Autowired
    private PortalOrderItemDao orderItemDao;
    @Autowired
    private SmsCouponHistoryMapper couponHistoryMapper;
    @Autowired
    private UmsMemberStatisticsInfoMapper memberStatisticsInfoMapper;
    @Autowired
    private RedisService redisService;
    @Value("${redis.key.orderId}")
    private String REDIS_KEY_ORDER_ID;
    @Value("${redis.database}")
    private String REDIS_DATABASE;
    @Value("${pay.account}")
    private String PAY_ACCOUNT;
    @Value("${pay.wxJspayUrl}")
    private String PAY_WX_JSPAY_URL;
    @Value("${pay.closeTradeOrderUrl}")
    private String PAY_CLOSE_TRADE_ORDER_URL;
    @Value("${pay.notifyUrl}")
    private String PAY_NOTIFY_URL;
    @Value("${pay.sign}")
    private String PAY_SIGN;
    @Value("${wx.appid}")
    private String WX_APPID;
    @Autowired
    private Environment env;
    @Autowired
    private PortalOrderDao portalOrderDao;
    @Autowired
    private OmsOrderSettingMapper orderSettingMapper;
    @Autowired
    private OmsOrderItemMapper orderItemMapper;
    @Autowired
    private CancelOrderSender cancelOrderSender;
    @Autowired
    private OmsPromotionService promotionService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private JdyService jdyService;
    @Autowired
    private PmsProductMapper pmsProductMapper;
    @Autowired
    private OmsOrderReturnApplyMapper omsOrderReturnApplyMapper;
    @Autowired
    private PmsSkuStockMapper pmsSkuStockMapper;
    @Autowired
    private SmsFlashPromotionProductRelationMapper flashPromotionProductRelationMapper;
    @Autowired
    private SmsFlashPromotionSessionMapper smsFlashPromotionSessionMapper;
    @Autowired
    private SmsFlashPromotionProductMemberRelationMapper flashPromotionProductMemberRelationMapper;
    @Autowired
    private WxService wxService;
    @Override
    public ConfirmOrderResult generateConfirmOrder(List<Long> cartIds) {
        ConfirmOrderResult result = new ConfirmOrderResult();
        //获取购物车信息
        UmsMember currentMember = memberService.getCurrentMember();
        List<CartPromotionItem> cartPromotionItemList = cartItemService.listPromotion(currentMember.getId(),cartIds);
        result.setCartPromotionItemList(cartPromotionItemList);
        //获取用户收货地址列表
        List<UmsMemberReceiveAddress> memberReceiveAddressList = memberReceiveAddressService.list();
        result.setMemberReceiveAddressList(memberReceiveAddressList);
        //获取用户可用优惠券列表
        List<SmsCouponHistoryDetail> couponHistoryDetailList = memberCouponService.listCart(cartPromotionItemList, 1);
        result.setCouponHistoryDetailList(couponHistoryDetailList);
        //获取用户积分
        result.setMemberIntegration(currentMember.getIntegration());
        //获取积分使用规则
        UmsIntegrationConsumeSetting integrationConsumeSetting = integrationConsumeSettingMapper.selectByPrimaryKey(1L);
        result.setIntegrationConsumeSetting(integrationConsumeSetting);
        //计算总金额、活动优惠、应付金额
        ConfirmOrderResult.CalcAmount calcAmount = calcCartAmount(cartPromotionItemList);
        result.setCalcAmount(calcAmount);
        return result;
    }

    @Override
    public ConfirmOrderResult generateConfirmOrder(OmsCartItemVO cartItem) throws ParseException {
        UmsMember currentMember = memberService.getCurrentMember();
        ConfirmOrderResult result = new ConfirmOrderResult();
        OmsCartItem omsCartItem = new OmsCartItem();
        List<OmsCartItem> cartItemList = new ArrayList<>();
        if (cartItem.getFlashPromotionId()!=null && cartItem.getFlashPromotionSessionId()!=null && cartItem.getFlashPromotionProductRelationId()!=null){
            SmsFlashPromotionProductRelation smsFlashPromotionProductRelation = flashPromotionProductRelationMapper.selectByPrimaryKey(cartItem.getFlashPromotionProductRelationId());
            SmsFlashPromotionProductMemberRelationExample example = new SmsFlashPromotionProductMemberRelationExample();
            example.createCriteria().andMemberIdEqualTo(currentMember.getId()).andPromotionProductRelationIdEqualTo(smsFlashPromotionProductRelation.getId());
            List<SmsFlashPromotionProductMemberRelation> smsFlashPromotionProductMemberRelations = flashPromotionProductMemberRelationMapper.selectByExample(example);
            SmsFlashPromotionSession smsFlashPromotionSession = smsFlashPromotionSessionMapper.selectByPrimaryKey(smsFlashPromotionProductRelation.getFlashPromotionSessionId());
            System.out.println(smsFlashPromotionSession);
            SimpleDateFormat sdf =   new SimpleDateFormat( "HH:mm:ss" );
            Date date= new Date();
            if (sdf.parse(sdf.format(date)).after(sdf.parse(sdf.format(smsFlashPromotionSession.getEndTime())))){
                Asserts.fail("秒杀已结束");
            }
            if (smsFlashPromotionProductRelation.getFlashPromotionResidue()==0){
                Asserts.fail("你来晚了，商品已经抢完了");
            }
            if(CollUtil.isNotEmpty(smsFlashPromotionProductMemberRelations)){
                if (smsFlashPromotionProductMemberRelations.get(0).getQuantity()>=smsFlashPromotionProductRelation.getFlashPromotionCount()){
                    Asserts.fail("你已经抢过了不能再抢了");
                }
            }
            cartItem.setMemberNickname(currentMember.getNickname());
            cartItem.setMemberId(currentMember.getId());
            cartItem.setCreateDate(new Date());
            cartItem.setDeleteStatus(0);
            cartItem.setPrice(smsFlashPromotionProductRelation.getFlashPromotionPrice());
            BeanUtils.copyProperties(cartItem,omsCartItem);
            cartItemList.add(omsCartItem);
            List<CartPromotionItem> cartPromotionItemList= promotionService.calcCartPromotion(cartItemList);
            result.setCartPromotionItemList(cartPromotionItemList);
            List<UmsMemberReceiveAddress> memberReceiveAddressList = memberReceiveAddressService.list();
            result.setMemberReceiveAddressList(memberReceiveAddressList);
            ConfirmOrderResult.CalcAmount calcAmount = new ConfirmOrderResult.CalcAmount();
            BigDecimal totalAmount = new BigDecimal("0");
            totalAmount = totalAmount.add(omsCartItem.getPrice().multiply(new BigDecimal(omsCartItem.getQuantity())));
            calcAmount.setTotalAmount(totalAmount);
            calcAmount.setPayAmount(totalAmount);
            result.setCalcAmount(calcAmount);
            result.setOrderType(new Long("1"));
            return result;
        }else{
            cartItem.setMemberNickname(currentMember.getNickname());
            cartItem.setMemberId(currentMember.getId());
            cartItem.setCreateDate(new Date());
            cartItem.setDeleteStatus(0);
            cartItem.setPrice(pmsSkuStockMapper.selectByPrimaryKey(cartItem.getProductSkuId()).getPrice());
            BeanUtils.copyProperties(cartItem,omsCartItem);
            cartItemList.add(omsCartItem);
            List<CartPromotionItem> cartPromotionItemList= promotionService.calcCartPromotion(cartItemList);
            result.setCartPromotionItemList(cartPromotionItemList);
            //获取用户收货地址列表
            List<UmsMemberReceiveAddress> memberReceiveAddressList = memberReceiveAddressService.list();
            result.setMemberReceiveAddressList(memberReceiveAddressList);
            //获取用户可用优惠券列表
            List<SmsCouponHistoryDetail> couponHistoryDetailList = memberCouponService.listCart(cartPromotionItemList, 1);
            System.out.println(couponHistoryDetailList);
            result.setCouponHistoryDetailList(couponHistoryDetailList);
            //获取用户积分
            result.setMemberIntegration(currentMember.getIntegration());
            //获取积分使用规则
            UmsIntegrationConsumeSetting integrationConsumeSetting = integrationConsumeSettingMapper.selectByPrimaryKey(1L);
            result.setIntegrationConsumeSetting(integrationConsumeSetting);
            //计算总金额、活动优惠、应付金额
            ConfirmOrderResult.CalcAmount calcAmount = calcCartAmount(cartPromotionItemList);
            result.setCalcAmount(calcAmount);
            result.setOrderType(new Long("0"));
            return result;
        }
    }

    @Override
    public Map<String, Object> generateOrder(OrderParam orderParam) {
        List<OmsOrderItem> orderItemList = new ArrayList<>();
        //获取购物车及优惠信息
        UmsMember currentMember = memberService.getCurrentMember();
        List<CartPromotionItem> cartPromotionItemList = cartItemService.listPromotion(currentMember.getId(), orderParam.getCartIds());
//        orderItemList= cartPromotionItemList.stream().map(cartPromotionItem -> {
//            OmsOrderItem orderItem = new OmsOrderItem();
//            BeanUtils.copyProperties(orderItem,cartPromotionItem);
//            return orderItem;
//        }).collect(Collectors.toList());
        for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            //生成下单商品信息
            OmsOrderItem orderItem = new OmsOrderItem();
            orderItem.setProductId(cartPromotionItem.getProductId());
            orderItem.setProductName(cartPromotionItem.getProductName());
            orderItem.setProductPic(cartPromotionItem.getProductPic());
            orderItem.setProductAttr(cartPromotionItem.getProductAttr());
            orderItem.setProductBrand(cartPromotionItem.getProductBrand());
            orderItem.setProductSn(cartPromotionItem.getProductSn());
            orderItem.setProductPrice(cartPromotionItem.getPrice());
            orderItem.setProductQuantity(cartPromotionItem.getQuantity());
            orderItem.setProductSkuId(cartPromotionItem.getProductSkuId());
            orderItem.setProductSkuCode(cartPromotionItem.getProductSkuCode());
            orderItem.setProductCategoryId(cartPromotionItem.getProductCategoryId());
            orderItem.setPromotionAmount(cartPromotionItem.getReduceAmount());
            orderItem.setPromotionName(cartPromotionItem.getPromotionMessage());
            orderItem.setGiftIntegration(cartPromotionItem.getIntegration());
            orderItem.setGiftGrowth(cartPromotionItem.getGrowth());
            orderItemList.add(orderItem);
        }
        //判断购物车中商品是否都有库存
        if (!hasStock(cartPromotionItemList)) {
            Asserts.fail("库存不足，无法下单");
        }
        //判断使用使用了优惠券
        if (CollUtil.isEmpty(orderParam.getCIds())) {
            //不用优惠券
            for (OmsOrderItem orderItem : orderItemList) {
                orderItem.setCouponAmount(new BigDecimal(0));
            }
        } else {
            System.out.println(cartPromotionItemList);
            //使用优惠券
            List<SmsCouponHistoryDetail> couponHistoryDetail = getUseCoupon(cartPromotionItemList, orderParam.getCIds());
            System.out.println("couponHistoryDetail===="+couponHistoryDetail);
            if (couponHistoryDetail == null) {
                Asserts.fail("该优惠券不可用");
            }
            System.out.println("orderItemList====="+orderItemList);
            //对下单商品的优惠券进行处理
            handleCouponAmount(orderItemList, couponHistoryDetail);
            System.out.println("++===+++=="+orderItemList.toString());
        }
        //判断是否使用积分
        if (orderParam.getUseIntegration() == null||orderParam.getUseIntegration().equals(0)) {
            //不使用积分
            for (OmsOrderItem orderItem : orderItemList) {
                orderItem.setIntegrationAmount(new BigDecimal(0));
            }
        } else {
            //使用积分
            BigDecimal totalAmount = calcTotalAmount(orderItemList);
            BigDecimal integrationAmount = getUseIntegrationAmount(orderParam.getUseIntegration(), totalAmount, currentMember, orderParam.getCouponId() != null);
            if (integrationAmount.compareTo(new BigDecimal(0)) == 0) {
                Asserts.fail("积分不可用");
            } else {
                //可用情况下分摊到可用商品中
                for (OmsOrderItem orderItem : orderItemList) {
                    BigDecimal perAmount = orderItem.getProductPrice().divide(totalAmount, 3, RoundingMode.HALF_EVEN).multiply(integrationAmount);
                    orderItem.setIntegrationAmount(perAmount);
                }
            }
        }
        //计算order_item的实付金额
        handleRealAmount(orderItemList);
        //进行库存锁定
        lockStock(cartPromotionItemList);
        //根据商品合计、运费、活动优惠、优惠券、积分计算应付金额
        OmsOrder order = new OmsOrder();
        order.setDiscountAmount(new BigDecimal(0));
        order.setTotalAmount(calcTotalAmount(orderItemList));
        order.setFreightAmount(new BigDecimal(0));
        order.setPromotionAmount(calcPromotionAmount(orderItemList));
        order.setPromotionInfo(getOrderPromotionInfo(orderItemList));
        order.setNote(orderParam.getNote());
        if (CollUtil.isEmpty(orderParam.getCIds())) {
            order.setCouponAmount(new BigDecimal(0));
        } else {
            String s = StringUtils.join(orderParam.getCIds().toArray(),",");
            System.out.println("id++++++===="+s);
            order.setCouponId(s);
            order.setCouponAmount(calcCouponAmount(orderItemList));
        }
        if (orderParam.getUseIntegration() == null) {
            order.setIntegration(0);
            order.setIntegrationAmount(new BigDecimal(0));
        } else {
            order.setIntegration(orderParam.getUseIntegration());
            order.setIntegrationAmount(calcIntegrationAmount(orderItemList));
        }
        order.setPayAmount(calcPayAmount(order));
        //转化为订单信息并插入数据库
        order.setMemberId(currentMember.getId());
        order.setCreateTime(new Date());
        order.setMemberUsername(currentMember.getUsername());
        //支付方式：0->未支付；1->支付宝；2->微信
        order.setPayType(orderParam.getPayType());
        //订单来源：0->PC订单；1->app订单
        order.setSourceType(1);
        //订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
        order.setStatus(0);
        //订单类型：0->正常订单；1->秒杀订单
        order.setOrderType(0);
        //收货人信息：姓名、电话、邮编、地址
        UmsMemberReceiveAddress address = memberReceiveAddressService.getItem(orderParam.getMemberReceiveAddressId());
        order.setReceiverName(address.getName());
        order.setReceiverPhone(address.getPhoneNumber());
        order.setReceiverPostCode(address.getPostCode());
        order.setReceiverProvince(address.getProvince());
        order.setReceiverCity(address.getCity());
        order.setReceiverRegion(address.getRegion());
        order.setReceiverDetailAddress(address.getDetailAddress());
        //0->未确认；1->已确认
        order.setConfirmStatus(0);
        order.setDeleteStatus(0);
        //计算赠送积分
        order.setIntegration(calcGifIntegration(orderItemList));
        //计算赠送成长值
        order.setGrowth(calcGiftGrowth(orderItemList));
        //生成订单号
        order.setOrderSn(generateOrderSn(order));
        //设置自动收货天数
        List<OmsOrderSetting> orderSettings = orderSettingMapper.selectByExample(new OmsOrderSettingExample());
        if(CollUtil.isNotEmpty(orderSettings)){
            order.setAutoConfirmDay(orderSettings.get(0).getConfirmOvertime());
        }
        // TODO: 2018/9/3 bill_*,delivery_*
        //插入order表和order_item表
        orderMapper.insert(order);
        UmsMemberStatisticsInfoExample memberStatisticsInfoExample = new UmsMemberStatisticsInfoExample();
        memberStatisticsInfoExample.createCriteria().andMemberIdEqualTo(order.getMemberId());
        List<UmsMemberStatisticsInfo> memberStatisticsInfoList = memberStatisticsInfoMapper.selectByExample(memberStatisticsInfoExample);
        if (CollUtil.isNotEmpty(memberStatisticsInfoList)){
            UmsMemberStatisticsInfo memberStatisticsInfo = memberStatisticsInfoList.get(0);
            memberStatisticsInfo.setOrderCount(memberStatisticsInfo.getOrderCount()+1);
            BigDecimal pay = new BigDecimal("0.00");
            pay=memberStatisticsInfo.getConsumeAmount();
            pay.add(order.getPayAmount());
            memberStatisticsInfo.setConsumeAmount(pay);
            memberStatisticsInfo.setRecentOrderTime(new Date());
            memberStatisticsInfoMapper.updateByPrimaryKeySelective(memberStatisticsInfo);
        }
        for (OmsOrderItem orderItem : orderItemList) {
            orderItem.setOrderId(order.getId());
            orderItem.setOrderSn(order.getOrderSn());
        }
        orderItemDao.insertList(orderItemList);
        //如使用优惠券更新优惠券使用状态
        System.out.println("322===="+order.getCouponId());
        if (order.getCouponId() != null) {
            updateCouponStatus(order.getCouponId(), currentMember.getId(), 1);
        }
        //如使用积分需要扣除积分
        if (orderParam.getUseIntegration() != null) {
            order.setUseIntegration(orderParam.getUseIntegration());
            memberService.updateIntegration(currentMember.getId(), currentMember.getIntegration() - orderParam.getUseIntegration());
        }
        //删除购物车中的下单商品
        deleteCartItemList(cartPromotionItemList, currentMember);
        //发送延迟消息取消订单
        sendDelayMessageCancelOrder(order.getId());
        Map<String, Object> result = new HashMap<>();
        result.put("order", order);
        result.put("orderItemList", orderItemList);
        return result;
    }

    @Override
    public Map<String, Object> productgenerateOrder(OrderParamVO orderParam) throws ParseException {
        if (orderParam.getFlashPromotionId()!=null && orderParam.getFlashPromotionSessionId()!=null && orderParam.getFlashPromotionProductRelationId()!=null){
            UmsMember currentMember = memberService.getCurrentMember();
            SmsFlashPromotionProductRelation smsFlashPromotionProductRelation = flashPromotionProductRelationMapper.selectByPrimaryKey(orderParam.getFlashPromotionProductRelationId());
            SmsFlashPromotionProductMemberRelationExample example = new SmsFlashPromotionProductMemberRelationExample();
            example.createCriteria().andMemberIdEqualTo(currentMember.getId()).andPromotionProductRelationIdEqualTo(smsFlashPromotionProductRelation.getId());
            List<SmsFlashPromotionProductMemberRelation> smsFlashPromotionProductMemberRelations = flashPromotionProductMemberRelationMapper.selectByExample(example);
            SmsFlashPromotionSession smsFlashPromotionSession = smsFlashPromotionSessionMapper.selectByPrimaryKey(smsFlashPromotionProductRelation.getFlashPromotionSessionId());
            System.out.println(smsFlashPromotionSession);
            SimpleDateFormat sdf =   new SimpleDateFormat( "HH:mm:ss" );
            Date date= new Date();
            if (sdf.parse(sdf.format(date)).after(sdf.parse(sdf.format(smsFlashPromotionSession.getEndTime())))){
                Asserts.fail("秒杀已结束");
            }
            if (smsFlashPromotionProductRelation.getFlashPromotionResidue()==0){
                Asserts.fail("你来晚了，商品已经抢完了");
            }
            if(CollUtil.isNotEmpty(smsFlashPromotionProductMemberRelations)){
                if (smsFlashPromotionProductMemberRelations.get(0).getQuantity()>=smsFlashPromotionProductRelation.getFlashPromotionCount()){
                    Asserts.fail("你已经抢过了不能再抢了");
                }
            }
            List<OmsOrderItem> orderItemList = new ArrayList<>();
            //ConfirmOrderResult result = new ConfirmOrderResult();
            List<OmsCartItem> cartItemList = new ArrayList<>();
            OmsCartItem omsCartItem = new OmsCartItem();
            BeanUtils.copyProperties(orderParam.getCartItem(),omsCartItem);
            omsCartItem.setMemberNickname(currentMember.getNickname());
            omsCartItem.setMemberId(currentMember.getId());
            omsCartItem.setCreateDate(new Date());
            omsCartItem.setDeleteStatus(0);
            cartItemList.add(omsCartItem);
            List<CartPromotionItem> cartPromotionItemList= promotionService.calcCartPromotion(cartItemList);
            //System.out.println(cartItemList);
            for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
                //生成下单商品信息
                OmsOrderItem orderItem = new OmsOrderItem();
                orderItem.setProductId(cartPromotionItem.getProductId());
                orderItem.setProductName(cartPromotionItem.getProductName());
                orderItem.setProductPic(cartPromotionItem.getProductPic());
                orderItem.setProductAttr(cartPromotionItem.getProductAttr());
                orderItem.setProductBrand(cartPromotionItem.getProductBrand());
                orderItem.setProductSn(cartPromotionItem.getProductSn());
                orderItem.setProductPrice(smsFlashPromotionProductRelation.getFlashPromotionPrice());
                orderItem.setProductQuantity(cartPromotionItem.getQuantity());
                orderItem.setProductSkuId(cartPromotionItem.getProductSkuId());
                orderItem.setProductSkuCode(cartPromotionItem.getProductSkuCode());
                orderItem.setProductCategoryId(cartPromotionItem.getProductCategoryId());
                orderItem.setPromotionAmount(cartPromotionItem.getReduceAmount());
                orderItem.setPromotionName(cartPromotionItem.getPromotionMessage());
                orderItem.setGiftIntegration(cartPromotionItem.getIntegration());
                orderItem.setGiftGrowth(cartPromotionItem.getGrowth());
                orderItemList.add(orderItem);
            }
            int residue=0;
            for (OmsOrderItem orderItem : orderItemList) {
                residue=residue+orderItem.getProductQuantity();
            }
            SmsFlashPromotionProductMemberRelation memberRelation = new SmsFlashPromotionProductMemberRelation();
            if(CollUtil.isNotEmpty(smsFlashPromotionProductMemberRelations)){
                memberRelation.setId(smsFlashPromotionProductMemberRelations.get(0).getId());
                memberRelation.setQuantity(smsFlashPromotionProductMemberRelations.get(0).getQuantity()+residue);
            }else{
                memberRelation.setQuantity(residue);
                memberRelation.setMemberId(currentMember.getId());
                memberRelation.setPromotionProductRelationId(smsFlashPromotionProductRelation.getId());
            }
            if (memberRelation.getQuantity()>smsFlashPromotionProductRelation.getFlashPromotionLimit()){
                Asserts.fail("超出限购量");
            }
            //判断购物车中商品是否都有库存
//            if (!hasStock(cartPromotionItemList)) {
//                Asserts.fail("库存不足，无法下单");
//            }
            //判断使用使用了优惠券
           // if (orderParam.getCouponId() == null) {
                //不用优惠券
                for (OmsOrderItem orderItem : orderItemList) {
                    orderItem.setCouponAmount(new BigDecimal(0));
                }
          //  } else {
                //使用优惠券
          //      List<Long> cIds = new ArrayList<>();
          //      cIds.add(orderParam.getCouponId());
             //   List<SmsCouponHistoryDetail> couponHistoryDetail = getUseCoupon(cartPromotionItemList, cIds);
           //     if (couponHistoryDetail == null) {
              //      Asserts.fail("该优惠券不可用");
             //   }
                //对下单商品的优惠券进行处理
           //     handleCouponAmount(orderItemList, couponHistoryDetail);
         //   }
            //判断是否使用积分
           // if (orderParam.getUseIntegration() == null||orderParam.getUseIntegration().equals(0)) {
                //不使用积分
                for (OmsOrderItem orderItem : orderItemList) {
                    orderItem.setIntegrationAmount(new BigDecimal(0));
                }
           // } else {
                //使用积分
            //    BigDecimal totalAmount = calcTotalAmount(orderItemList);
           //     BigDecimal integrationAmount = getUseIntegrationAmount(orderParam.getUseIntegration(), totalAmount, currentMember, orderParam.getCouponId() != null);
            //    if (integrationAmount.compareTo(new BigDecimal(0)) == 0) {
            //        Asserts.fail("积分不可用");
            //    } else {
                    //可用情况下分摊到可用商品中
           //         for (OmsOrderItem orderItem : orderItemList) {
            //            BigDecimal perAmount = orderItem.getProductPrice().divide(totalAmount, 3, RoundingMode.HALF_EVEN).multiply(integrationAmount);
            //            orderItem.setIntegrationAmount(perAmount);
            //        }
            //    }
          //  }
            //计算order_item的实付金额
            //handleRealAmount(orderItemList);
            //进行库存锁定
            //lockStock(cartPromotionItemList);
            //根据商品合计、运费、活动优惠、优惠券、积分计算应付金额
            OmsOrder order = new OmsOrder();
            order.setDiscountAmount(new BigDecimal(0));

            order.setTotalAmount(calcTotalAmount(orderItemList));
            order.setFreightAmount(new BigDecimal(0));
            order.setPromotionAmount(new BigDecimal(0));
            order.setPromotionInfo("限时秒杀");
            order.setNote(orderParam.getNote());
//            if (orderParam.getCouponId() == null) {
                order.setCouponAmount(new BigDecimal(0));
//            } else {
//                order.setCouponId(orderParam.getCouponId().toString());
//                order.setCouponAmount(calcCouponAmount(orderItemList));
//            }
            //if (orderParam.getUseIntegration() == null) {
                order.setIntegration(0);
                order.setIntegrationAmount(new BigDecimal(0));
           // } else {
              //  order.setIntegration(orderParam.getUseIntegration());
               // order.setIntegrationAmount(calcIntegrationAmount(orderItemList));
           // }
            order.setPayAmount(calcPayAmount(order));
            //转化为订单信息并插入数据库
            order.setMemberId(currentMember.getId());
            order.setCreateTime(new Date());
            order.setMemberUsername(currentMember.getUsername());
            //支付方式：0->未支付；1->支付宝；2->微信
            order.setPayType(orderParam.getPayType());
            //订单来源：0->PC订单；1->app订单
            order.setSourceType(1);
            //订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
            order.setStatus(0);
            //订单类型：0->正常订单；1->秒杀订单
            order.setOrderType(1);
            //收货人信息：姓名、电话、邮编、地址
            UmsMemberReceiveAddress address = memberReceiveAddressService.getItem(orderParam.getMemberReceiveAddressId());
            order.setReceiverName(address.getName());
            order.setReceiverPhone(address.getPhoneNumber());
            order.setReceiverPostCode(address.getPostCode());
            order.setReceiverProvince(address.getProvince());
            order.setReceiverCity(address.getCity());
            order.setReceiverRegion(address.getRegion());
            order.setReceiverDetailAddress(address.getDetailAddress());
            //0->未确认；1->已确认
            order.setConfirmStatus(0);
            order.setDeleteStatus(0);
            //计算赠送积分
            //order.setIntegration(calcGifIntegration(orderItemList));
            //计算赠送成长值
            //order.setGrowth(calcGiftGrowth(orderItemList));
            //生成订单号
            order.setOrderSn(generateOrderSn(order));
            //设置自动收货天数
            List<OmsOrderSetting> orderSettings = orderSettingMapper.selectByExample(new OmsOrderSettingExample());
            if(CollUtil.isNotEmpty(orderSettings)){
                order.setAutoConfirmDay(orderSettings.get(0).getConfirmOvertime());
            }
            // TODO: 2018/9/3 bill_*,delivery_*
            //插入order表和order_item表
            orderMapper.insert(order);
            UmsMemberStatisticsInfoExample memberStatisticsInfoExample = new UmsMemberStatisticsInfoExample();
            memberStatisticsInfoExample.createCriteria().andMemberIdEqualTo(order.getMemberId());
            List<UmsMemberStatisticsInfo> memberStatisticsInfoList = memberStatisticsInfoMapper.selectByExample(memberStatisticsInfoExample);
            if (CollUtil.isNotEmpty(memberStatisticsInfoList)){
                UmsMemberStatisticsInfo memberStatisticsInfo = memberStatisticsInfoList.get(0);
                memberStatisticsInfo.setOrderCount(memberStatisticsInfo.getOrderCount()+1);
                BigDecimal pay = new BigDecimal("0.00");
                pay=memberStatisticsInfo.getConsumeAmount();
                pay.add(order.getPayAmount());
                memberStatisticsInfo.setConsumeAmount(pay);
                memberStatisticsInfo.setRecentOrderTime(new Date());
                memberStatisticsInfoMapper.updateByPrimaryKeySelective(memberStatisticsInfo);
            }
            for (OmsOrderItem orderItem : orderItemList) {
                orderItem.setOrderId(order.getId());
                orderItem.setOrderSn(order.getOrderSn());
            }

            orderItemDao.insertList(orderItemList);
            //如使用优惠券更新优惠券使用状态
            if (orderParam.getCouponId() != null) {
                updateCouponStatus(orderParam.getCouponId().toString(), currentMember.getId(), 1);
            }
            //如使用积分需要扣除积分
            if (orderParam.getUseIntegration() != null) {
                order.setUseIntegration(orderParam.getUseIntegration());
                memberService.updateIntegration(currentMember.getId(), currentMember.getIntegration() - orderParam.getUseIntegration());
            }
            //删除购物车中的下单商品
            deleteCartItemList(cartPromotionItemList, currentMember);
            //发送延迟消息取消订单
            sendDelayMessageCancelOrder(order.getId());
            Map<String, Object> result1 = new HashMap<>();
            result1.put("order", order);
            result1.put("orderItemList", orderItemList);

            System.out.println("residue="+residue);
            smsFlashPromotionProductRelation.setFlashPromotionResidue(smsFlashPromotionProductRelation.getFlashPromotionResidue()-residue);
            flashPromotionProductRelationMapper.updateByPrimaryKeySelective(smsFlashPromotionProductRelation);
            if(CollUtil.isNotEmpty(smsFlashPromotionProductMemberRelations)){
                flashPromotionProductMemberRelationMapper.updateByPrimaryKeySelective(memberRelation);
            }else {
                flashPromotionProductMemberRelationMapper.insert(memberRelation);
            }

            return result1;
        }else{
            List<OmsOrderItem> orderItemList = new ArrayList<>();
            //ConfirmOrderResult result = new ConfirmOrderResult();
            UmsMember currentMember = memberService.getCurrentMember();
            List<OmsCartItem> cartItemList = new ArrayList<>();
            OmsCartItem omsCartItem = new OmsCartItem();
            BeanUtils.copyProperties(orderParam.getCartItem(),omsCartItem);
            omsCartItem.setMemberNickname(currentMember.getNickname());
            omsCartItem.setMemberId(currentMember.getId());
            omsCartItem.setCreateDate(new Date());
            omsCartItem.setDeleteStatus(0);
            cartItemList.add(omsCartItem);
            List<CartPromotionItem> cartPromotionItemList= promotionService.calcCartPromotion(cartItemList);
            System.out.println(cartItemList);
            for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
                //生成下单商品信息
                OmsOrderItem orderItem = new OmsOrderItem();
                orderItem.setProductId(cartPromotionItem.getProductId());
                orderItem.setProductName(cartPromotionItem.getProductName());
                orderItem.setProductPic(cartPromotionItem.getProductPic());
                orderItem.setProductAttr(cartPromotionItem.getProductAttr());
                orderItem.setProductBrand(cartPromotionItem.getProductBrand());
                orderItem.setProductSn(cartPromotionItem.getProductSn());
                orderItem.setProductPrice(cartPromotionItem.getPrice());
                orderItem.setProductQuantity(cartPromotionItem.getQuantity());
                orderItem.setProductSkuId(cartPromotionItem.getProductSkuId());
                orderItem.setProductSkuCode(cartPromotionItem.getProductSkuCode());
                orderItem.setProductCategoryId(cartPromotionItem.getProductCategoryId());
                orderItem.setPromotionAmount(cartPromotionItem.getReduceAmount());
                orderItem.setPromotionName(cartPromotionItem.getPromotionMessage());
                orderItem.setGiftIntegration(cartPromotionItem.getIntegration());
                orderItem.setGiftGrowth(cartPromotionItem.getGrowth());

                orderItemList.add(orderItem);
            }
            //判断购物车中商品是否都有库存
            if (!hasStock(cartPromotionItemList)) {
                Asserts.fail("库存不足，无法下单");
            }
            //判断使用使用了优惠券
            if (orderParam.getCouponId() == null) {
                //不用优惠券
                for (OmsOrderItem orderItem : orderItemList) {
                    orderItem.setCouponAmount(new BigDecimal(0));
                }
            } else {
                //使用优惠券
                List<Long> cIds = new ArrayList<>();
                cIds.add(orderParam.getCouponId());
                List<SmsCouponHistoryDetail> couponHistoryDetail = getUseCoupon(cartPromotionItemList, cIds);
                if (couponHistoryDetail == null) {
                    Asserts.fail("该优惠券不可用");
                }
                //对下单商品的优惠券进行处理
                handleCouponAmount(orderItemList, couponHistoryDetail);
            }
            //判断是否使用积分
            if (orderParam.getUseIntegration() == null||orderParam.getUseIntegration().equals(0)) {
                //不使用积分
                for (OmsOrderItem orderItem : orderItemList) {
                    orderItem.setIntegrationAmount(new BigDecimal(0));
                }
            } else {
                //使用积分
                BigDecimal totalAmount = calcTotalAmount(orderItemList);
                BigDecimal integrationAmount = getUseIntegrationAmount(orderParam.getUseIntegration(), totalAmount, currentMember, orderParam.getCouponId() != null);
                if (integrationAmount.compareTo(new BigDecimal(0)) == 0) {
                    Asserts.fail("积分不可用");
                } else {
                    //可用情况下分摊到可用商品中
                    for (OmsOrderItem orderItem : orderItemList) {
                        BigDecimal perAmount = orderItem.getProductPrice().divide(totalAmount, 3, RoundingMode.HALF_EVEN).multiply(integrationAmount);
                        orderItem.setIntegrationAmount(perAmount);
                    }
                }
            }
            //计算order_item的实付金额
            handleRealAmount(orderItemList);
            //进行库存锁定
            lockStock(cartPromotionItemList);
            //根据商品合计、运费、活动优惠、优惠券、积分计算应付金额
            OmsOrder order = new OmsOrder();
            order.setDiscountAmount(new BigDecimal(0));
            order.setTotalAmount(calcTotalAmount(orderItemList));
            order.setFreightAmount(new BigDecimal(0));
            order.setPromotionAmount(calcPromotionAmount(orderItemList));
            order.setPromotionInfo(getOrderPromotionInfo(orderItemList));
            order.setNote(orderParam.getNote());
            if (orderParam.getCouponId() == null) {
                order.setCouponAmount(new BigDecimal(0));
            } else {
                order.setCouponId(orderParam.getCouponId().toString());
                order.setCouponAmount(calcCouponAmount(orderItemList));
            }
            if (orderParam.getUseIntegration() == null) {
                order.setIntegration(0);
                order.setIntegrationAmount(new BigDecimal(0));
            } else {
                order.setIntegration(orderParam.getUseIntegration());
                order.setIntegrationAmount(calcIntegrationAmount(orderItemList));
            }
            order.setPayAmount(calcPayAmount(order));
            //转化为订单信息并插入数据库
            order.setMemberId(currentMember.getId());
            order.setCreateTime(new Date());
            order.setMemberUsername(currentMember.getUsername());
            //支付方式：0->未支付；1->支付宝；2->微信
            order.setPayType(orderParam.getPayType());
            //订单来源：0->PC订单；1->app订单
            order.setSourceType(1);
            //订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
            order.setStatus(0);
            //订单类型：0->正常订单；1->秒杀订单
            order.setOrderType(0);
            //收货人信息：姓名、电话、邮编、地址
            UmsMemberReceiveAddress address = memberReceiveAddressService.getItem(orderParam.getMemberReceiveAddressId());
            order.setReceiverName(address.getName());
            order.setReceiverPhone(address.getPhoneNumber());
            order.setReceiverPostCode(address.getPostCode());
            order.setReceiverProvince(address.getProvince());
            order.setReceiverCity(address.getCity());
            order.setReceiverRegion(address.getRegion());
            order.setReceiverDetailAddress(address.getDetailAddress());
            //0->未确认；1->已确认
            order.setConfirmStatus(0);
            order.setDeleteStatus(0);
            //计算赠送积分
            order.setIntegration(calcGifIntegration(orderItemList));
            //计算赠送成长值
            order.setGrowth(calcGiftGrowth(orderItemList));
            //生成订单号
            order.setOrderSn(generateOrderSn(order));
            //设置自动收货天数
            List<OmsOrderSetting> orderSettings = orderSettingMapper.selectByExample(new OmsOrderSettingExample());
            if(CollUtil.isNotEmpty(orderSettings)){
                order.setAutoConfirmDay(orderSettings.get(0).getConfirmOvertime());
            }
            // TODO: 2018/9/3 bill_*,delivery_*
            //插入order表和order_item表
            orderMapper.insert(order);
            UmsMemberStatisticsInfoExample memberStatisticsInfoExample = new UmsMemberStatisticsInfoExample();
            memberStatisticsInfoExample.createCriteria().andMemberIdEqualTo(order.getMemberId());
            List<UmsMemberStatisticsInfo> memberStatisticsInfoList = memberStatisticsInfoMapper.selectByExample(memberStatisticsInfoExample);
            if (CollUtil.isNotEmpty(memberStatisticsInfoList)){
                UmsMemberStatisticsInfo memberStatisticsInfo = memberStatisticsInfoList.get(0);
                memberStatisticsInfo.setOrderCount(memberStatisticsInfo.getOrderCount()+1);
                BigDecimal pay = new BigDecimal("0.00");
                pay=memberStatisticsInfo.getConsumeAmount();
                pay.add(order.getPayAmount());
                memberStatisticsInfo.setConsumeAmount(pay);
                memberStatisticsInfo.setRecentOrderTime(new Date());
                memberStatisticsInfoMapper.updateByPrimaryKeySelective(memberStatisticsInfo);
            }
            for (OmsOrderItem orderItem : orderItemList) {
                orderItem.setOrderId(order.getId());
                orderItem.setOrderSn(order.getOrderSn());
            }
            orderItemDao.insertList(orderItemList);
            //如使用优惠券更新优惠券使用状态
            if (orderParam.getCouponId() != null) {
                updateCouponStatus(orderParam.getCouponId().toString(), currentMember.getId(), 1);
            }
            //如使用积分需要扣除积分
            if (orderParam.getUseIntegration() != null) {
                order.setUseIntegration(orderParam.getUseIntegration());
                memberService.updateIntegration(currentMember.getId(), currentMember.getIntegration() - orderParam.getUseIntegration());
            }
            //删除购物车中的下单商品
            deleteCartItemList(cartPromotionItemList, currentMember);
            //发送延迟消息取消订单
            sendDelayMessageCancelOrder(order.getId());
            Map<String, Object> result1 = new HashMap<>();
            result1.put("order", order);
            result1.put("orderItemList", orderItemList);
            return result1;
        }
    }

    @Override
    public Integer paySuccess(Long orderId, Integer payType) {
        //修改订单支付状态
        OmsOrder order = new OmsOrder();
        order.setId(orderId);
        order.setStatus(1);
        order.setPaymentTime(new Date());
        order.setPayType(payType);
        orderMapper.updateByPrimaryKeySelective(order);
        //恢复所有下单商品的锁定库存，扣减真实库存
        OmsOrderDetail orderDetail = portalOrderDao.getDetail(orderId);
        int count = portalOrderDao.updateSkuStock(orderDetail.getOrderItemList());
        return count;
    }

    @Override
    public Integer cancelTimeOutOrder() {
        Integer count=0;
        OmsOrderSetting orderSetting = orderSettingMapper.selectByPrimaryKey(1L);
        //查询超时、未支付的订单及订单详情
        List<OmsOrderDetail> timeOutOrders = portalOrderDao.getTimeOutOrders(orderSetting.getNormalOrderOvertime());
        if (CollectionUtils.isEmpty(timeOutOrders)) {
            return count;
        }
        //修改订单状态为交易取消
        List<Long> ids = new ArrayList<>();
        for (OmsOrderDetail timeOutOrder : timeOutOrders) {
            ids.add(timeOutOrder.getId());
        }
        portalOrderDao.updateOrderStatus(ids, 4);
        for (OmsOrderDetail timeOutOrder : timeOutOrders) {
            //解除订单商品库存锁定
            portalOrderDao.releaseSkuStockLock(timeOutOrder.getOrderItemList());
            //修改优惠券使用状态
            updateCouponStatus(timeOutOrder.getCouponId(), timeOutOrder.getMemberId(), 0);
            //返还使用积分
            if (timeOutOrder.getUseIntegration() != null) {
                UmsMember member = memberService.getById(timeOutOrder.getMemberId());
                memberService.updateIntegration(timeOutOrder.getMemberId(), member.getIntegration() + timeOutOrder.getUseIntegration());
            }

        }
        return timeOutOrders.size();
    }

    @Override
    public void cancelOrder(Long orderId) {
        //查询未付款的取消订单
        OmsOrderExample example = new OmsOrderExample();
        example.createCriteria().andIdEqualTo(orderId).andStatusEqualTo(0).andDeleteStatusEqualTo(0);
        List<OmsOrder> cancelOrderList = orderMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(cancelOrderList)) {
            return;
        }
        OmsOrder cancelOrder = cancelOrderList.get(0);
        if (cancelOrder != null) {
            //修改订单状态为取消
            cancelOrder.setStatus(4);
            orderMapper.updateByPrimaryKeySelective(cancelOrder);
            OmsOrderItemExample orderItemExample = new OmsOrderItemExample();
            orderItemExample.createCriteria().andOrderIdEqualTo(orderId);
            List<OmsOrderItem> orderItemList = orderItemMapper.selectByExample(orderItemExample);
            //解除订单商品库存锁定
            if (!CollectionUtils.isEmpty(orderItemList)) {
                portalOrderDao.releaseSkuStockLock(orderItemList);
            }
            //修改优惠券使用状态
            updateCouponStatus(cancelOrder.getCouponId(), cancelOrder.getMemberId(), 0);
            //返还使用积分
            if (cancelOrder.getUseIntegration() != null) {
                UmsMember member = memberService.getById(cancelOrder.getMemberId());
                memberService.updateIntegration(cancelOrder.getMemberId(), member.getIntegration() + cancelOrder.getUseIntegration());
            }
        }
    }

    @Override
    public void sendDelayMessageCancelOrder(Long orderId) {
        //获取订单超时时间
        OmsOrderSetting orderSetting = orderSettingMapper.selectByPrimaryKey(1L);
        long delayTimes = orderSetting.getNormalOrderOvertime() * 60 * 1000;
        //发送延迟消息
        cancelOrderSender.sendMessage(orderId, delayTimes);
    }

    @Override
    public void confirmReceiveOrder(Long orderId) {
        UmsMember member = memberService.getCurrentMember();
        OmsOrder order = orderMapper.selectByPrimaryKey(orderId);
        if(!member.getId().equals(order.getMemberId())){
            Asserts.fail("不能确认他人订单！");
        }
        if(order.getStatus()!=2){
            Asserts.fail("该订单还未发货！");
        }
        order.setStatus(3);
        order.setConfirmStatus(1);
        order.setReceiveTime(new Date());
        orderMapper.updateByPrimaryKey(order);
    }

    @Override
    public CommonPage<OmsOrderDetail> list(Integer status, Integer pageNum, Integer pageSize) {
        if(status==-1){
            status = null;
        }
        UmsMember member = memberService.getCurrentMember();
        PageHelper.startPage(pageNum,pageSize);
        OmsOrderExample orderExample = new OmsOrderExample();
        OmsOrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andDeleteStatusEqualTo(0)
                .andMemberIdEqualTo(member.getId());
        if(status!=null){
            criteria.andStatusEqualTo(status);
        }
        orderExample.setOrderByClause("create_time desc");
        List<OmsOrder> orderList = orderMapper.selectByExample(orderExample);
        CommonPage<OmsOrder> orderPage = CommonPage.restPage(orderList);
        //设置分页信息
        CommonPage<OmsOrderDetail> resultPage = new CommonPage<>();
        resultPage.setPageNum(orderPage.getPageNum());
        resultPage.setPageSize(orderPage.getPageSize());
        resultPage.setTotal(orderPage.getTotal());
        resultPage.setTotalPage(orderPage.getTotalPage());
        if(CollUtil.isEmpty(orderList)){
            return resultPage;
        }
        //设置数据信息
        List<Long> orderIds = orderList.stream().map(OmsOrder::getId).collect(Collectors.toList());
        OmsOrderItemExample orderItemExample = new OmsOrderItemExample();
        orderItemExample.createCriteria().andOrderIdIn(orderIds);
        List<OmsOrderItem> orderItemList = orderItemMapper.selectByExample(orderItemExample);
        List<OmsOrderDetail> orderDetailList = new ArrayList<>();
        for (OmsOrder omsOrder : orderList) {
            OmsOrderDetail orderDetail = new OmsOrderDetail();
            BeanUtil.copyProperties(omsOrder,orderDetail);
            List<OmsOrderItem> relatedItemList = orderItemList.stream().filter(item -> item.getOrderId().equals(orderDetail.getId())).collect(Collectors.toList());
            for (OmsOrderItem omsOrderItem :relatedItemList){
                OmsOrderReturnApplyExample omsOrderReturnApplyExample = new OmsOrderReturnApplyExample();
                omsOrderReturnApplyExample.createCriteria().andOrderIdEqualTo(omsOrderItem.getOrderId()).andProductIdEqualTo(omsOrderItem.getProductId());
                List<OmsOrderReturnApply> omsOrderReturnApplies = omsOrderReturnApplyMapper.selectByExample(omsOrderReturnApplyExample);
                OmsOrderReturnApply omsOrderReturnApply = new OmsOrderReturnApply();
                if (!omsOrderReturnApplies.isEmpty()){
                    omsOrderReturnApply=  omsOrderReturnApplies.get(0);
                }
                omsOrderItem.setOmsOrderReturnApply(omsOrderReturnApply);
            }

            orderDetail.setOrderItemList(relatedItemList);
            orderDetailList.add(orderDetail);
        }
        resultPage.setList(orderDetailList);
        return resultPage;
    }

    @Override
    public OmsOrderDetail detail(Long orderId) {
        OmsOrder omsOrder = orderMapper.selectByPrimaryKey(orderId);
        OmsOrderItemExample example = new OmsOrderItemExample();
        example.createCriteria().andOrderIdEqualTo(orderId);
        List<OmsOrderItem> orderItemList = orderItemMapper.selectByExample(example);
        for (OmsOrderItem o: orderItemList){
            o.setPmsSkuStock(pmsSkuStockMapper.selectByPrimaryKey(o.getProductSkuId()));
        }
        OmsOrderDetail orderDetail = new OmsOrderDetail();
        BeanUtil.copyProperties(omsOrder,orderDetail);
        orderDetail.setOrderItemList(orderItemList);
        return orderDetail;
    }

    @Override
    public void deleteOrder(Long orderId) {
        UmsMember member = memberService.getCurrentMember();
        OmsOrder order = orderMapper.selectByPrimaryKey(orderId);
        if(!member.getId().equals(order.getMemberId())){
            Asserts.fail("不能删除他人订单！");
        }
        if(order.getStatus()==3||order.getStatus()==4){
            order.setDeleteStatus(1);
            orderMapper.updateByPrimaryKey(order);
        }else{
            Asserts.fail("只能删除已完成或已关闭的订单！");
        }
    }

    @Override
    public String pay(Long orderId, Integer payType) {
        UmsMember member = memberService.getCurrentMember();
        OmsOrderExample example = new OmsOrderExample();
        example.createCriteria().andIdEqualTo(orderId).andDeleteStatusEqualTo(0).andStatusEqualTo(0);
        OmsOrder omsOrder = orderMapper.selectByExample(example).get(0);
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
//        if (omsOrder!=null && omsOrder.getTongGuanSn()!=null){
//            Map<String,Object> map = new HashMap<>();
//            map.put("account",PAY_ACCOUNT);
//            map.put("lowOrderId",omsOrder.getOrderSn());
//            map.put("upOrderId",omsOrder.getTongGuanSn());
//            String s = "account="+map.get("account")+"&lowOrderId="+map.get("lowOrderId")+"&upOrderId="+map.get("upOrderId")+"&key="+PAY_SIGN;
//            map.put("sign", KeyedDigestMD5.getKeyedDigest("",s).toUpperCase());
//            String data = JSONObject.fromObject(map).toString();
//            String res = HttpKit.post(PAY_CLOSE_TRADE_ORDER_URL,data,headers);
//            Map<String, Object> resMap = JSON.parseObject(res,Map.class);
//            if ((int)resMap.get("status")==101){
//                System.out.println("error++++"+resMap.get("messages"));
//                Asserts.fail("支付出错");
//            }
//        }
        Map<String,Object> map = new HashMap<>();
        //appid
        map.put("appId",WX_APPID);
        //openId
        map.put("openId",member.getOpenId());
        //聚合支付账号
        map.put("account",PAY_ACCOUNT);
        //金额（元）
//        BigDecimal pay = new BigDecimal(0.00);
//        pay=;
        map.put("payMoney", omsOrder.getPayAmount().subtract(omsOrder.getDiscountAmount()).toString());
        //下游订单号
        map.put("lowOrderId",omsOrder.getOrderSn());
        //商品订单描述
        String body = "SATE SHOP-"+omsOrder.getOrderSn();
        map.put("body",body);
        //下游接收支付结果的url地址
        map.put("notifyUrl",PAY_NOTIFY_URL);
        //支付方式 0：微信，1：支付宝，4：银联
//        if (payType==1){
//            map.put("payType","0");
//        }else if (payType==2){
//            map.put("payType","1");
//        }
        String ss = "account="+map.get("account")+"&appId="+map.get("appId")+"&body="+map.get("body")+"&lowOrderId="+map.get("lowOrderId")+"&notifyUrl="+map.get("notifyUrl")+"&openId="+map.get("openId")+"&payMoney="+map.get("payMoney")+"&key="+PAY_SIGN;
        System.out.println(ss);
        map.put("sign", KeyedDigestMD5.getKeyedDigest("",ss).toUpperCase());
        String data = JSONObject.fromObject(map).toString();
        String res1 = HttpKit.post(PAY_WX_JSPAY_URL,data,headers);
        Map<String, Object> resMap1 = JSON.parseObject(res1,Map.class);
        System.out.println(resMap1.toString());
        if ((int)resMap1.get("status")==100){
            OmsOrder omsOrder1 = new OmsOrder();
            omsOrder1.setId(omsOrder.getId());
            omsOrder1.setTongGuanSn(resMap1.get("upOrderId").toString());
            orderMapper.updateByPrimaryKeySelective(omsOrder1);
            return resMap1.get("pay_info").toString();
        }
        System.out.println("error++++"+resMap1.get("messages"));
        return "error";
    }

    @Override
    public void updatePay(PayResultVO payResultVO)  {
        try {
            if (payResultVO.getState()==0){
                System.out.println("111111======"+payResultVO.getLowOrderId());
                OmsOrderExample example = new OmsOrderExample();
                example.createCriteria().andOrderSnEqualTo(payResultVO.getLowOrderId());
                OmsOrder omsOrder = orderMapper.selectByExample(example).get(0);
                SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
                String time = payResultVO.getPayTime();
                System.out.println(time);
                omsOrder.setTongGuanSn(payResultVO.getUpOrderId());
                omsOrder.setPaymentTime(sdf.parse(time));
                omsOrder.setOrderSn(payResultVO.getLowOrderId());
                omsOrder.setPayType(2);
                omsOrder.setStatus(1);
                System.out.println(omsOrder.getId());
                OmsOrderDetail orderDetail = portalOrderDao.getDetail(omsOrder.getId());
                System.out.println("orderDetail====="+orderDetail);
                int count = portalOrderDao.updateSkuStock(orderDetail.getOrderItemList());
//                rabbitTemplate.convertAndSend(env.getProperty("mq.pay.exchange.order"),env.getProperty("mq.pay.queue.order"),payResultVO);
                List<JdyOrderVO> jdyOrderVOS = jdyService.salesSlip(omsOrder);
                System.out.println("jdyOrderVOS"+jdyOrderVOS);
                if (jdyOrderVOS!=null){
                    if (jdyOrderVOS.get(0).getNumber()!="" &&jdyOrderVOS.get(0).getNumber().length()!=0){
                        omsOrder.setJdySn(jdyOrderVOS.get(0).getNumber());
                    }
                }
                int i = orderMapper.updateByPrimaryKeySelective(omsOrder);
                //订阅消息
                //messageSend(omsOrder);
                OmsOrderItemExample omsOrderItemExample = new OmsOrderItemExample();
                omsOrderItemExample.createCriteria().andOrderIdEqualTo(omsOrder.getId());
                List<OmsOrderItem> omsOrderItems = orderItemMapper.selectByExample(omsOrderItemExample);
                for (OmsOrderItem omsOrderItem : omsOrderItems){
                    PmsProduct pmsProduct = pmsProductMapper.selectByPrimaryKey(omsOrderItem.getProductId());
                    pmsProduct.setSale(pmsProduct.getSale()+omsOrderItem.getProductQuantity());
                    pmsProductMapper.updateByPrimaryKeySelective(pmsProduct);
                }
            }else {
                Asserts.fail("支付失败");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    @Override
    public List<OrderTrackingVO> orderTracking(Long id) {
        OmsOrder omsOrder = orderMapper.selectByPrimaryKey(id);
        List<OrderTrackingVO> ots=new ArrayList<>();
        SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        ots.add(new OrderTrackingVO("订单已提交，等待付款",sdf.format(omsOrder.getCreateTime())));
        if (omsOrder.getPaymentTime()!=null){
            ots.add(new OrderTrackingVO("订单付款成功,等待发货",sdf.format(omsOrder.getPaymentTime())));
        }

        if (omsOrder.getDeliveryTime()!=null){
            ots.add(new OrderTrackingVO("已发货，包囊正在等待揽收",sdf.format(omsOrder.getPaymentTime())));
            QueryTrackReq queryTrackReq = new QueryTrackReq();
            QueryTrackParam queryTrackParam = new QueryTrackParam();
            queryTrackParam.setCom(new FastCoding().getMap().get(omsOrder.getDeliveryCompany()));
            queryTrackParam.setNum(omsOrder.getDeliverySn());
            queryTrackReq.setCustomer("26B7D406A83CF9067BD93D4BDECEA8AE");
            queryTrackReq.setParam(queryTrackParam);
            queryTrackReq.setSign(SignUtils.sign(JSONObject.fromObject(queryTrackParam).toString()+"ZpPkoKff3913"+queryTrackReq.getCustomer()));
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            CloseableHttpResponse resp = null;
            HttpResult result = new HttpResult();
            try {
                Map<String, String> params = objectToMap(queryTrackReq);
                HttpPost httpPost = new HttpPost("https://poll.kuaidi100.com/poll/query.do");
                if (params != null && params.size() > 0) {
                    List<NameValuePair> list = new ArrayList<NameValuePair>();
                    for (Map.Entry<String, String> entry : params.entrySet()) {
                        list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                    }
                    httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
                }
                resp = httpClient.execute(httpPost);
                String body = EntityUtils.toString(resp.getEntity(), "UTF-8");
                Map<String,Object> res = JSON.parseObject(body,Map.class);
                List<LogisticsVO> item = JSON.parseArray(res.get("data").toString(),LogisticsVO.class);
                Collections.reverse(item);
                for (LogisticsVO lgs:item){
                    ots.add(new OrderTrackingVO(lgs.getContext(),lgs.getTime()));
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Collections.reverse(ots);
        return ots;
    }

    @Override
    public void orderRefund(Long orderId) {
        System.out.println(orderId);
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        OmsOrder omsOrder = orderMapper.selectByPrimaryKey(orderId);
        System.out.println(omsOrder);
        Map<String,Object> map1 = new HashMap<>();
        if (omsOrder.getJdySn()!=null){
            map1.put("items", Arrays.asList(omsOrder.getJdySn()));
            String data1 = JSONObject.fromObject(map1).toString();
            String res1 = com.macro.mall.common.utils.HttpKit.post("https://api.kingdee.com/jdyscm/delivery/delete?access_token="+env.getProperty("jdy.token")+"&dbId="+env.getProperty("jdy.dbId"),data1,headers);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("account",env.getProperty("pay.account"));
        map.put("upOrderId",omsOrder.getTongGuanSn());
        map.put("refundMoney",omsOrder.getPayAmount().subtract(omsOrder.getDiscountAmount()).toString());
        String s = "account="+map.get("account")+"&refundMoney="+map.get("refundMoney")+"&upOrderId="+map.get("upOrderId")+"&key="+env.getProperty("pay.sign");
        map.put("sign", com.macro.mall.common.utils.KeyedDigestMD5.getKeyedDigest("",s).toUpperCase());
        String data = JSONObject.fromObject(map).toString();
        String res = com.macro.mall.common.utils.HttpKit.post(env.getProperty("pay.refundUrl"),data,headers);
        Map<String, Object> resMap = JSON.parseObject(res,Map.class);
        if ((int)resMap.get("status")==100 && resMap.get("state").toString().equals("5")){
            omsOrder.setStatus(4);
            orderMapper.updateByPrimaryKeySelective(omsOrder);
        }else {
            Asserts.fail("退款失败");
        }
    }

    @Override
    public void notice(Long id) {
        OmsOrder omsOrder = orderMapper.selectByPrimaryKey(id);
        OmsOrderItemExample omsOrderItemExample = new OmsOrderItemExample();
        omsOrderItemExample.createCriteria().andOrderIdEqualTo(omsOrder.getId());
        List<OmsOrderItem> omsOrderItems = orderItemMapper.selectByExample(omsOrderItemExample);
        UmsMember member = memberService.getById(omsOrder.getMemberId());
        OmsOrderItemExample example1 = new OmsOrderItemExample();
        example1.createCriteria().andOrderIdEqualTo(omsOrder.getId());
        List<OmsOrderItem> omsOrderItems1 = orderItemMapper.selectByExample(example1);
        String s = "";
        for (int x = 0;x<omsOrderItems1.size();x++){
            s+=omsOrderItems.get(x).getProductName()+",";
        }
        if (s.length()>20){
            s=s.substring(0,16);
            s+="...";
        }else{
            s=s.substring(0,s.length()-1);
        }

        SimpleDateFormat sdf1 =   new SimpleDateFormat( "yyyy年MM月dd日 HH:mm:ss" );
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        String accessToken = wxService.accessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+accessToken;
        String templateId = "Pr0IXWN0-okXLPJHxQbEGxtmx0eq8MtbQXe5tBk7kpc";
        Map<String, Object> d = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> value = new HashMap<>();
        Map<String, Object> value2 = new HashMap<>();
        Map<String, Object> value3 = new HashMap<>();
        Map<String, Object> value4 = new HashMap<>();
        Map<String, Object> value5 = new HashMap<>();
        value.put("value",omsOrder.getOrderSn());
        value2.put("value",s);
        value3.put("value",omsOrder.getPayAmount().toString());
        value4.put("value",sdf1.format(new Date()));
        value5.put("value","支付成功，稍后请留意物流信息");
        d.put("number5",value);
        d.put("thing1",value2);
        d.put("amount2",value3);
        d.put("time4",value4);
        d.put("thing8",value5);
        data.put("touser",member.getOpenId());
        data.put("template_id",templateId);
        data.put("page","/pages/order/orderDetails?orderId="+omsOrder.getId());
        data.put("data",d);
        System.out.println(data);
        String data1 = JSONObject.fromObject(data).toString();
        String res = com.macro.mall.common.utils.HttpKit.post(url, data1, headers);
        Map<String, Object> resMap = JSON.parseObject(res, Map.class);
        System.out.println(resMap);
    }

    /**
     * 生成18位订单编号:8位日期+2位平台号码+2位支付方式+6位以上自增id
     */
    private String generateOrderSn(OmsOrder order) {
        StringBuilder sb = new StringBuilder();
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String key = REDIS_DATABASE+":"+ REDIS_KEY_ORDER_ID + date;
        Long increment = redisService.incr(key, 1);
        System.out.println("+++++++++"+increment);
        sb.append(date);
        sb.append(String.format("%02d", order.getSourceType()));
        sb.append(String.format("%02d", order.getPayType()));
        String incrementStr = increment.toString();
        if (incrementStr.length() <= 6) {
            sb.append(String.format("%06d", increment));
        } else {
            sb.append(incrementStr);
        }
        return sb.toString();
    }

    /**
     * 删除下单商品的购物车信息
     */
    private void deleteCartItemList(List<CartPromotionItem> cartPromotionItemList, UmsMember currentMember) {
        List<Long> ids = new ArrayList<>();
        for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            ids.add(cartPromotionItem.getId());
        }
        cartItemService.delete(currentMember.getId(), ids);
    }

    /**
     * 计算该订单赠送的成长值
     */
    private Integer calcGiftGrowth(List<OmsOrderItem> orderItemList) {
        Integer sum = 0;
        for (OmsOrderItem orderItem : orderItemList) {
            sum = sum + orderItem.getGiftGrowth() * orderItem.getProductQuantity();
        }
        return sum;
    }

    /**
     * 计算该订单赠送的积分
     */
    private Integer calcGifIntegration(List<OmsOrderItem> orderItemList) {
        int sum = 0;
        for (OmsOrderItem orderItem : orderItemList) {
            sum += orderItem.getGiftIntegration() * orderItem.getProductQuantity();
        }
        return sum;
    }

    /**
     * 将优惠券信息更改为指定状态
     *
     * @param couponId  优惠券id
     * @param memberId  会员id
     * @param useStatus 0->未使用；1->已使用
     */
    private void updateCouponStatus(String couponId, Long memberId, Integer useStatus) {
        if (couponId == null ) return;
        //查询第一张优惠券
        List<Long> ids= Arrays.stream(couponId.split(","))
                .map(s -> Long.parseLong(s.trim()))
                .collect(Collectors.toList());
        SmsCouponHistoryExample example = new SmsCouponHistoryExample();
        example.createCriteria().andMemberIdEqualTo(memberId)
                .andCouponIdIn(ids).andUseStatusEqualTo(useStatus == 0 ? 1 : 0);
        List<SmsCouponHistory> couponHistoryList = couponHistoryMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(couponHistoryList)) {
            for (SmsCouponHistory s : couponHistoryList){
                s.setUseTime(new Date());
                s.setUseStatus(useStatus);
                couponHistoryMapper.updateByPrimaryKeySelective(s);
            }
        }
    }

    private void handleRealAmount(List<OmsOrderItem> orderItemList) {
        for (OmsOrderItem orderItem : orderItemList) {
            //原价-促销优惠-优惠券抵扣-积分抵扣
            BigDecimal realAmount = orderItem.getProductPrice()
                    .subtract(orderItem.getPromotionAmount())
                    .subtract(orderItem.getCouponAmount())
                    .subtract(orderItem.getIntegrationAmount());
            orderItem.setRealAmount(realAmount);
        }
    }

    /**
     * 获取订单促销信息
     */
    private String getOrderPromotionInfo(List<OmsOrderItem> orderItemList) {
        StringBuilder sb = new StringBuilder();
        for (OmsOrderItem orderItem : orderItemList) {
            sb.append(orderItem.getPromotionName());
            sb.append(";");
        }
        String result = sb.toString();
        if (result.endsWith(";")) {
            result = result.substring(0, result.length() - 1);
        }
        return result;
    }

    /**
     * 计算订单应付金额
     */
    private BigDecimal calcPayAmount(OmsOrder order) {
        //总金额+运费-促销优惠-优惠券优惠-积分抵扣
        BigDecimal payAmount = order.getTotalAmount()
                .add(order.getFreightAmount())
                .subtract(order.getPromotionAmount())
                .subtract(order.getCouponAmount())
                .subtract(order.getIntegrationAmount());
        return payAmount;
    }

    /**
     * 计算订单优惠券金额
     */
    private BigDecimal calcIntegrationAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal integrationAmount = new BigDecimal(0);
        for (OmsOrderItem orderItem : orderItemList) {
            if (orderItem.getIntegrationAmount() != null) {
                integrationAmount = integrationAmount.add(orderItem.getIntegrationAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
            }
        }
        return integrationAmount;
    }

    /**
     * 计算订单优惠券金额
     */
    private BigDecimal calcCouponAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal couponAmount = new BigDecimal(0);
        for (OmsOrderItem orderItem : orderItemList) {
            if (orderItem.getCouponAmount() != null) {
                couponAmount = couponAmount.add(orderItem.getCouponAmount());
            }
        }
        return couponAmount;
    }

    /**
     * 计算订单活动优惠
     */
    private BigDecimal calcPromotionAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal promotionAmount = new BigDecimal(0);
        for (OmsOrderItem orderItem : orderItemList) {
            if (orderItem.getPromotionAmount() != null) {
                promotionAmount = promotionAmount.add(orderItem.getPromotionAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
            }
        }
        return promotionAmount;
    }

    /**
     * 获取可用积分抵扣金额
     *
     * @param useIntegration 使用的积分数量
     * @param totalAmount    订单总金额
     * @param currentMember  使用的用户
     * @param hasCoupon      是否已经使用优惠券
     */
    private BigDecimal getUseIntegrationAmount(Integer useIntegration, BigDecimal totalAmount, UmsMember currentMember, boolean hasCoupon) {
        BigDecimal zeroAmount = new BigDecimal(0);
        //判断用户是否有这么多积分
        if (useIntegration.compareTo(currentMember.getIntegration()) > 0) {
            return zeroAmount;
        }
        //根据积分使用规则判断是否可用
        //是否可与优惠券共用
        UmsIntegrationConsumeSetting integrationConsumeSetting = integrationConsumeSettingMapper.selectByPrimaryKey(1L);
        if (hasCoupon && integrationConsumeSetting.getCouponStatus().equals(0)) {
            //不可与优惠券共用
            return zeroAmount;
        }
        //是否达到最低使用积分门槛
        if (useIntegration.compareTo(integrationConsumeSetting.getUseUnit()) < 0) {
            return zeroAmount;
        }
        //是否超过订单抵用最高百分比
        BigDecimal integrationAmount = new BigDecimal(useIntegration).divide(new BigDecimal(integrationConsumeSetting.getUseUnit()), 2, RoundingMode.HALF_EVEN);
        BigDecimal maxPercent = new BigDecimal(integrationConsumeSetting.getMaxPercentPerOrder()).divide(new BigDecimal(100), 2, RoundingMode.HALF_EVEN);
        if (integrationAmount.compareTo(totalAmount.multiply(maxPercent)) > 0) {
            return zeroAmount;
        }
        return integrationAmount;
    }

    /**
     * 对优惠券优惠进行处理
     *
     * @param orderItemList       order_item列表
     * @param couponHistoryDetails 可用优惠券详情
     */
    private void handleCouponAmount(List<OmsOrderItem> orderItemList, List<SmsCouponHistoryDetail> couponHistoryDetails) {
        for (SmsCouponHistoryDetail couponHistoryDetail: couponHistoryDetails){
            SmsCoupon coupon = couponHistoryDetail.getCoupon();
            if (coupon.getUseType().equals(0)) {
                //全场通用
                calcPerCouponAmount(orderItemList, coupon);
            } else if (coupon.getUseType().equals(1)) {
                //指定分类
                List<OmsOrderItem> couponOrderItemList = getCouponOrderItemByRelation(couponHistoryDetail, orderItemList, 0);
                calcPerCouponAmount(couponOrderItemList, coupon);
            } else if (coupon.getUseType().equals(2)) {
                //指定商品
                List<OmsOrderItem> couponOrderItemList = getCouponOrderItemByRelation(couponHistoryDetail, orderItemList, 1);
                calcPerCouponAmount(couponOrderItemList, coupon);
            }
        }
    }

    /**
     * 对每个下单商品进行优惠券金额分摊的计算
     *
     * @param orderItemList 可用优惠券的下单商品商品
     */
    private void calcPerCouponAmount(List<OmsOrderItem> orderItemList, SmsCoupon coupon) {
        BigDecimal totalAmount = calcTotalAmount(orderItemList);
        for (OmsOrderItem orderItem : orderItemList) {
            //(商品价格/可用商品总价)*优惠券面额
            BigDecimal couponAmount = orderItem.getProductPrice().divide(totalAmount, 3, RoundingMode.HALF_EVEN).multiply(coupon.getAmount());
            if (orderItem.getCouponAmount()!=null){
                System.out.println("@@@@"+couponAmount);
                orderItem.setCouponAmount(couponAmount.add(orderItem.getCouponAmount()));
                System.out.println("@@@@"+orderItem.getCouponAmount());
            }else{
                orderItem.setCouponAmount(couponAmount);
            }

        }
    }

    /**
     * 获取与优惠券有关系的下单商品
     *
     * @param couponHistoryDetail 优惠券详情
     * @param orderItemList       下单商品
     * @param type                使用关系类型：0->相关分类；1->指定商品
     */
    private List<OmsOrderItem> getCouponOrderItemByRelation(SmsCouponHistoryDetail couponHistoryDetail, List<OmsOrderItem> orderItemList, int type) {
        List<OmsOrderItem> result = new ArrayList<>();
        if (type == 0) {
            List<Long> categoryIdList = new ArrayList<>();
            for (SmsCouponProductCategoryRelation productCategoryRelation : couponHistoryDetail.getCategoryRelationList()) {
                categoryIdList.add(productCategoryRelation.getProductCategoryId());
            }
            for (OmsOrderItem orderItem : orderItemList) {
                if (categoryIdList.contains(orderItem.getProductCategoryId())) {
                    result.add(orderItem);
                }
            }
        } else if (type == 1) {
            List<Long> productIdList = new ArrayList<>();
            for (SmsCouponProductRelation productRelation : couponHistoryDetail.getProductRelationList()) {
                productIdList.add(productRelation.getProductId());
            }
            for (OmsOrderItem orderItem : orderItemList) {
                if (productIdList.contains(orderItem.getProductId())) {
                    result.add(orderItem);
                }
            }
        }
        return result;
    }

    /**
     * 获取该用户可以使用的优惠券
     *
     * @param cartPromotionItemList 购物车优惠列表
     * @param cIds              使用优惠券id
     */
    private List<SmsCouponHistoryDetail> getUseCoupon(List<CartPromotionItem> cartPromotionItemList, List<Long> cIds) {
        List<SmsCouponHistoryDetail> couponHistoryDetailList = memberCouponService.listCart(cartPromotionItemList, 1);
        System.out.println("couponHistoryDetailList=="+couponHistoryDetailList.toString());
        List<SmsCouponHistoryDetail> couponHistoryDetailList1=new ArrayList<>();
        for (SmsCouponHistoryDetail couponHistoryDetail : couponHistoryDetailList) {
            System.out.println("couponHistoryDetail=="+couponHistoryDetail);
            for(Long id: cIds){
                //System.out.println("id"+id);
                if (couponHistoryDetail.getCouponId().equals(id)) {
                    couponHistoryDetailList1.add(couponHistoryDetail);
                    break;
                }
            }
        }
        return couponHistoryDetailList1;
    }

    /**
     * 计算总金额
     */
    private BigDecimal calcTotalAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal totalAmount = new BigDecimal("0");
        for (OmsOrderItem item : orderItemList) {
            totalAmount = totalAmount.add(item.getProductPrice().multiply(new BigDecimal(item.getProductQuantity())));
        }
        return totalAmount;
    }

    /**
     * 锁定下单商品的所有库存
     */
    private void lockStock(List<CartPromotionItem> cartPromotionItemList) {
        for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            PmsSkuStock skuStock = skuStockMapper.selectByPrimaryKey(cartPromotionItem.getProductSkuId());
            skuStock.setLockStock(skuStock.getLockStock() + cartPromotionItem.getQuantity());
            skuStockMapper.updateByPrimaryKeySelective(skuStock);
        }
    }

    /**
     * 判断下单商品是否都有库存
     */
    private boolean hasStock(List<CartPromotionItem> cartPromotionItemList) {
        for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            if (cartPromotionItem.getRealStock()==null||cartPromotionItem.getRealStock() <= 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * 计算购物车中商品的价格
     */
    private ConfirmOrderResult.CalcAmount calcCartAmount(List<CartPromotionItem> cartPromotionItemList) {
        ConfirmOrderResult.CalcAmount calcAmount = new ConfirmOrderResult.CalcAmount();
        calcAmount.setFreightAmount(new BigDecimal(0));
        BigDecimal totalAmount = new BigDecimal("0");
        BigDecimal promotionAmount = new BigDecimal("0");
        for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            totalAmount = totalAmount.add(cartPromotionItem.getPrice().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
            promotionAmount = promotionAmount.add(cartPromotionItem.getReduceAmount().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
        }
        calcAmount.setTotalAmount(totalAmount);
        calcAmount.setPromotionAmount(promotionAmount);
        calcAmount.setPayAmount(totalAmount.subtract(promotionAmount));
        return calcAmount;
    }
    public static Map<String, String> objectToMap(Object obj) throws IllegalAccessException {
        if (obj == null) {
            return null;
        }
        Map<String, String> map = new HashMap<String,String>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            String fieldValue = "";
            if (field.getType()== String.class || field.getType() == Integer.class || field.getType() == int.class){
                fieldValue = field.get(obj)==null?"": field.get(obj).toString();
            }else {
                fieldValue = JSONObject.fromObject(field.get(obj)).toString();
            }
            map.put(fieldName, fieldValue);
        }
        return map;
    }
}
